package com.aquarium.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.xmlpull.v1.XmlSerializer;

import android.content.Context;
import android.os.Environment;
import android.util.Log;
import android.util.Xml;
import android.widget.Toast;

import com.aquarium.R;
import com.aquarium.alarm.AlarmManager;

public class ConfigDOM {
	static String ALARMCONFIG = "alarmconfig";

	public static void writeAlarmConfig(String path, Context context) {
		AlarmManager alarmManager = AlarmManager.getInstance(context);
		File xmlFile = new File(Environment.getExternalStorageDirectory()
				.getAbsolutePath() + File.separator + path);

		try {
			if (!xmlFile.exists()) {
				xmlFile.createNewFile();
			} else {
				xmlFile.deleteOnExit();
				xmlFile.createNewFile();
			}
			FileOutputStream outStream = new FileOutputStream(xmlFile);
			XmlSerializer serializer = Xml.newSerializer();
			serializer.setOutput(outStream, "UTF-8");
			serializer.startDocument("UTF-8", true);
			serializer.setFeature(
					"http://xmlpull.org/v1/doc/features.html#indent-output",
					true);
			serializer.startTag(null, ALARMCONFIG);

			serializer.startTag(null, AlarmManager.GET_PH_INTERVAL_KEY);
			serializer.text(alarmManager.getPhAlarmInterval() + "");
			serializer.endTag(null, AlarmManager.GET_PH_INTERVAL_KEY);

			serializer.startTag(null, AlarmManager.GET_PH_MAX_KEY);
			serializer.text(alarmManager.getPhMax() + "");
			serializer.endTag(null, AlarmManager.GET_PH_MAX_KEY);

			serializer.startTag(null, AlarmManager.GET_PH_MIN_KEY);
			serializer.text(alarmManager.getPhMax() + "");
			serializer.endTag(null, AlarmManager.GET_PH_MIN_KEY);

			serializer
					.startTag(null, AlarmManager.GET_TEMPERATURE_INTERVAL_KEY);
			serializer.text(alarmManager.getTemperatureAlarmInterval() + "");
			serializer.endTag(null, AlarmManager.GET_TEMPERATURE_INTERVAL_KEY);

			serializer.startTag(null, AlarmManager.GET_TEMPERATURE_MAX_KEY);
			serializer.text(alarmManager.getTemperatureMax() + "");
			serializer.endTag(null, AlarmManager.GET_TEMPERATURE_MAX_KEY);

			serializer.startTag(null, AlarmManager.GET_TEMPERATURE_MIN_KEY);
			serializer.text(alarmManager.getTemperatureMin() + "");
			serializer.endTag(null, AlarmManager.GET_TEMPERATURE_MIN_KEY);

			serializer.startTag(null, AlarmManager.GET_OXYGEN_INTERVAL_KEY);
			serializer.text(alarmManager.getOxygenAlarmInterval() + "");
			serializer.endTag(null, AlarmManager.GET_OXYGEN_INTERVAL_KEY);

			serializer.startTag(null, AlarmManager.GET_OXYGEN_MAX_KEY);
			serializer.text(alarmManager.getOxygenMax() + "");
			serializer.endTag(null, AlarmManager.GET_OXYGEN_MAX_KEY);

			serializer.startTag(null, AlarmManager.GET_OXYGEN_MIN_KEY);
			serializer.text(alarmManager.getOxygenMin() + "");
			serializer.endTag(null, AlarmManager.GET_OXYGEN_MIN_KEY);

			serializer.startTag(null,
					AlarmManager.GET_CONDUCTIVITY_INTERVAL_KEY);
			serializer.text(alarmManager.getConductivityAlarmInterval() + "");
			serializer.endTag(null, AlarmManager.GET_CONDUCTIVITY_INTERVAL_KEY);

			serializer.startTag(null, AlarmManager.GET_CONDUCTIVITY_MAX_KEY);
			serializer.text(alarmManager.getConductivityMax() + "");
			serializer.endTag(null, AlarmManager.GET_CONDUCTIVITY_MAX_KEY);

			serializer.startTag(null, AlarmManager.GET_CONDUCTIVITY_MIN_KEY);
			serializer.text(alarmManager.getConductivityMin() + "");
			serializer.endTag(null, AlarmManager.GET_CONDUCTIVITY_MIN_KEY);

			serializer
					.startTag(null, AlarmManager.GET_WATER_LEVEL_INTERVAL_KEY);
			serializer.text(alarmManager.getWaterLevelInterval() + "");
			serializer.endTag(null, AlarmManager.GET_WATER_LEVEL_INTERVAL_KEY);

			serializer.startTag(null, AlarmManager.GET_WATER_LEVEL_MAX_KEY);
			serializer.text(alarmManager.getWaterLevelMax() + "");
			serializer.endTag(null, AlarmManager.GET_WATER_LEVEL_MAX_KEY);

			serializer.startTag(null, AlarmManager.GET_WATER_LEVEL_MIN_KEY);
			serializer.text(alarmManager.getWaterLevelMin() + "");
			serializer.endTag(null, AlarmManager.GET_WATER_LEVEL_MIN_KEY);

			serializer.endTag(null, ALARMCONFIG);
			serializer.endDocument();
			serializer.flush();
			outStream.flush();
			outStream.close();
			Toast.makeText(context, R.string.finish, Toast.LENGTH_LONG).show();
		} catch (FileNotFoundException e1) {
			Toast.makeText(context, R.string.error, Toast.LENGTH_LONG).show();
			e1.printStackTrace();
		} catch (UnsupportedEncodingException e1) {
			Toast.makeText(context, R.string.error, Toast.LENGTH_LONG).show();
			e1.printStackTrace();
		} catch (Exception e) {
			Toast.makeText(context, R.string.error, Toast.LENGTH_LONG).show();
			e.printStackTrace();
		}

	}

	public static void readAlarmConfig(String path, Context context) {
		Element element;
		Document doc;
		AlarmManager alarmManager = AlarmManager.getInstance(context);
		try {
			File file = new File(Environment.getExternalStorageDirectory()
					.getAbsolutePath() + File.separator + path);
			if (!file.exists()) {
				Toast.makeText(context, R.string.file_read_error,
						Toast.LENGTH_LONG).show();
			}
			InputStream inputStream = new FileInputStream(file);
			DocumentBuilderFactory dbFactory = DocumentBuilderFactory
					.newInstance();

			DocumentBuilder dbBuilder = dbFactory.newDocumentBuilder();
			doc = dbBuilder.parse(inputStream);
			element = doc.getDocumentElement();
			NodeList childNodes = element.getChildNodes();
			for (int j = 0; j < childNodes.getLength(); j++) {
				if (childNodes.item(j).getNodeType() == Node.ELEMENT_NODE) {
					String tagName = childNodes.item(j).getNodeName();
					String nodeValue = childNodes.item(j).getFirstChild()
							.getNodeValue();
					Log.d("", tagName + ":" + nodeValue);
					if (AlarmManager.GET_PH_INTERVAL_KEY.equals(tagName)) {
						alarmManager.setPhAlarmInterval(Integer
								.valueOf(nodeValue));
					}
					if (AlarmManager.GET_PH_MAX_KEY.equals(tagName)) {
						alarmManager.setPhMax(Float.parseFloat(nodeValue));
					}
					if (AlarmManager.GET_PH_MIN_KEY.equals(tagName)) {
						alarmManager.setPhMin(Float.parseFloat(nodeValue));
					}
					if (AlarmManager.GET_TEMPERATURE_INTERVAL_KEY
							.equals(tagName)) {
						alarmManager.setTemperatureAlarmInterval(Integer
								.parseInt(nodeValue));
					}
					if (AlarmManager.GET_TEMPERATURE_MAX_KEY.equals(tagName)) {
						alarmManager.setTemperatureMax(Float
								.parseFloat(nodeValue));
					}
					if (AlarmManager.GET_TEMPERATURE_MIN_KEY.equals(tagName)) {
						alarmManager.setTemperatureMin(Float
								.parseFloat(nodeValue));
					}
					if (AlarmManager.GET_OXYGEN_INTERVAL_KEY.equals(tagName)) {
						alarmManager.setOxygenAlarmInterval(Integer
								.parseInt(nodeValue));
					}
					if (AlarmManager.GET_OXYGEN_MAX_KEY.equals(tagName)) {
						alarmManager.setOxygenMax(Float.parseFloat(nodeValue));
					}
					if (AlarmManager.GET_OXYGEN_MIN_KEY.equals(tagName)) {
						alarmManager.setOxygenMin(Float.parseFloat(nodeValue));
					}

					if (AlarmManager.GET_CONDUCTIVITY_INTERVAL_KEY
							.equals(tagName)) {
						alarmManager.setConductivityAlarmInterval(Integer
								.parseInt(nodeValue));
					}
					if (AlarmManager.GET_CONDUCTIVITY_MAX_KEY.equals(tagName)) {
						alarmManager.setConductivityMax(Float
								.parseFloat(nodeValue));
					}
					if (AlarmManager.GET_CONDUCTIVITY_MIN_KEY.equals(tagName)) {
						alarmManager.setConductivityMin(Float
								.parseFloat(nodeValue));
					}

					if (AlarmManager.GET_WATER_LEVEL_INTERVAL_KEY
							.equals(tagName)) {
						alarmManager.setWaterLevelAlarmInterval(Integer
								.parseInt(nodeValue));
					}
					if (AlarmManager.GET_WATER_LEVEL_MAX_KEY.equals(tagName)) {
						alarmManager.setWaterLevelMax(Float
								.parseFloat(nodeValue));
					}
					if (AlarmManager.GET_WATER_LEVEL_MIN_KEY.equals(tagName)) {
						alarmManager.setWaterLevelMin(Float
								.parseFloat(nodeValue));
					}
				}
			}
			Toast.makeText(context, R.string.finish, Toast.LENGTH_LONG).show();
		} catch (FileNotFoundException e) {
			Toast.makeText(context, R.string.error, Toast.LENGTH_LONG).show();
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			Toast.makeText(context, R.string.error, Toast.LENGTH_LONG).show();
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			Toast.makeText(context, R.string.error, Toast.LENGTH_LONG).show();
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			Toast.makeText(context, R.string.error, Toast.LENGTH_LONG).show();
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	// public void copyFile(Context mContext) {
	// // 得到DOM解析器的工厂实例
	// DocumentBuilderFactory dbFactory = DocumentBuilderFactory
	// .newInstance();
	// // 从DOM工厂中获得DOM解析器
	// DocumentBuilder dbBuilder = dbFactory.newDocumentBuilder();
	// // 创建文档树模型对象
	// doc = dbBuilder.newDocument();
	// if (doc != null) {
	//
	// alarmconfig = doc.createElement(ALARMCONFIG);
	//
	// mPhMin = doc.createElement(AlarmManager.GET_PH_MIN_KEY);
	// mPhMin.appendChild(doc.createTextNode(alarmManager.getPhMin()
	// + ""));
	// alarmconfig.appendChild(mPhMin);
	//
	// mPhMax = doc.createElement(AlarmManager.GET_PH_MAX_KEY);
	// mPhMax.appendChild(doc.createTextNode(alarmManager.getPhMax()
	// + ""));
	// alarmconfig.appendChild(mPhMax);
	//
	// mPhAlarmInterval = doc
	// .createElement(AlarmManager.GET_PH_INTERVAL_KEY);
	// mPhAlarmInterval.appendChild(doc.createTextNode(alarmManager
	// .getPhAlarmInterval() + ""));
	// alarmconfig.appendChild(mPhAlarmInterval);
	//
	// mTemperatureAlarmInterval = doc
	// .createElement(AlarmManager.GET_TEMPERATURE_INTERVAL_KEY);
	// mTemperatureAlarmInterval.appendChild(doc
	// .createTextNode(alarmManager
	// .getTemperatureAlarmInterval() + ""));
	// alarmconfig.appendChild(mTemperatureAlarmInterval);
	//
	// mTemperatureMax = doc
	// .createElement(AlarmManager.GET_TEMPERATURE_MAX_KEY);
	// mTemperatureMax.appendChild(doc.createTextNode(alarmManager
	// .getTemperatureMax() + ""));
	// alarmconfig.appendChild(mTemperatureMax);
	//
	// mTemperatureMin = doc
	// .createElement(AlarmManager.GET_TEMPERATURE_MIN_KEY);
	// mTemperatureMin.appendChild(doc.createTextNode(alarmManager
	// .getTemperatureMin() + ""));
	// alarmconfig.appendChild(mTemperatureMin);
	//
	// mOxygenAlarmInterval = doc
	// .createElement(AlarmManager.GET_OXYGEN_INTERVAL_KEY);
	// mOxygenAlarmInterval.appendChild(doc
	// .createTextNode(alarmManager.getOxygenAlarmInterval()
	// + ""));
	// alarmconfig.appendChild(mOxygenAlarmInterval);
	//
	// mOxygenMax = doc.createElement(AlarmManager.GET_OXYGEN_MAX_KEY);
	// mOxygenMax.appendChild(doc.createTextNode(alarmManager
	// .getOxygenMax() + ""));
	// alarmconfig.appendChild(mOxygenMax);
	//
	// mOxygenMin = doc.createElement(AlarmManager.GET_OXYGEN_MIN_KEY);
	// mOxygenMin.appendChild(doc.createTextNode(alarmManager
	// .getOxygenMin() + ""));
	// alarmconfig.appendChild(mOxygenMin);
	//
	// mConductivityAlarmInterval = doc
	// .createElement(AlarmManager.GET_CONDUCTIVITY_INTERVAL_KEY);
	// mConductivityAlarmInterval.appendChild(doc
	// .createTextNode(alarmManager
	// .getConductivityAlarmInterval() + ""));
	// alarmconfig.appendChild(mConductivityAlarmInterval);
	//
	// mConductivityMax = doc
	// .createElement(AlarmManager.GET_CONDUCTIVITY_MAX_KEY);
	// mConductivityMax.appendChild(doc.createTextNode(alarmManager
	// .getConductivityMax() + ""));
	// alarmconfig.appendChild(mConductivityMax);
	//
	// mConductivityMin = doc
	// .createElement(AlarmManager.GET_CONDUCTIVITY_MIN_KEY);
	// mConductivityMin.appendChild(doc.createTextNode(alarmManager
	// .getConductivityMin() + ""));
	// alarmconfig.appendChild(mConductivityMin);
	//
	// mWaterLevelAlarmInterval = doc
	// .createElement(AlarmManager.GET_WATER_LEVEL_INTERVAL_KEY);
	// mWaterLevelAlarmInterval.appendChild(doc
	// .createTextNode(alarmManager.getWaterLevelInterval()
	// + ""));
	// alarmconfig.appendChild(mWaterLevelAlarmInterval);
	//
	// mWaterLevelMax = doc
	// .createElement(AlarmManager.GET_WATER_LEVEL_MAX_KEY);
	// mWaterLevelMax.appendChild(doc.createTextNode(alarmManager
	// .getWaterLevelMax() + ""));
	// alarmconfig.appendChild(mWaterLevelMax);
	//
	// mWaterLevelMin = doc
	// .createElement(AlarmManager.GET_WATER_LEVEL_MIN_KEY);
	// mWaterLevelMax.appendChild(doc.createTextNode(alarmManager
	// .getWaterLevelMin() + ""));
	// alarmconfig.appendChild(mWaterLevelMin);
	//
	// // 添加到文档树中
	// doc.appendChild(alarmconfig);
	// }
}
